var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;//导出的列
var paras;//查询条件

var params = new Object({
	init : function(){
		this.tac_status=0;
		this.eNodeBID_status=0;
		this.village_status=0;
	},
	
	setDimensionParam : function(dimension){
		if(dimension == 'area'){
			if($("#areaBox_tac").is(':checked')){
			  this.tac_status=1;
		    }
			if($("#areaBox_eNodeBID").is(':checked')){
				this.eNodeBID_status=1;
			}
			if($("#areaBox_village").is(':checked')){
				this.village_status=1;
			}
		}
	},
	setParam : function(){
		this.init();
		this.timeSize = $('input:radio[name="timeSize"]:checked').val();
		this.dimension = $('input:radio[name="radio"]:checked').val();
		if(this.dimension == '5'){//区域
			this.dimension = 'area';
		}else if(this.dimension == '0'){//用户组
			this.dimension = 'userGroup';
		}else if(this.dimension == '1'){//用户
			this.dimension = 'user';
		}else if(this.dimension == '2'){//终端类型
			this.dimension = 'terminal';
		}else if(this.dimension == '3'){//APN
			this.dimension = 'apn';
		}
		this.setDimensionParam(this.dimension);
	}
});
$(function() {
	$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	//getList();
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});

	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select:function(event,ui){
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();  
	$("#apnId").combobox();

	showArearList("area");
	
})

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();
	
	$.ajax({
		url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
				+ terminalBrand,
		type : 'POST',
		dataType : 'JSON',
		error : function() {
			alert('Error loading data!');
		},
		success : function(msg) {
			$("#terminalModelId").remove();
			$("#terminalModelTD").append($("<select id='terminalModelId' name='terminalModelId'></select>"));
			$("#terminalModelId").combobox();
			var list = msg.terminalModelList;
			$.each(eval(list), function(i, item) {
					$(
							"<option value='" + item.imei + "'>" + item.terminal_model
							+ "</option>").appendTo(
									$("#terminalModelId"));
			});
		}
	});	
}

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();
	
	$.ajax({
		url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
				+ terminalBrand,
		type : 'POST',
		dataType : 'JSON',
		error : function() {
			alert('Error loading data!');
		},
		success : function(msg) {
			$("#terminalModelId").remove();
			$("#terminalModelTD").append($("<select id='terminalModelId' name='terminalModelId'></select>"));
			$("#terminalModelId").combobox();
			var list = msg.terminalModelList;
			$.each(eval(list), function(i, item) {
					$(
							"<option value='" + item.terminal_model + "'>" + item.terminal_model
							+ "</option>").appendTo(
									$("#terminalModelId"));
			});
		}
	});	
}

/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 6; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}

/**
 * 页面校验
 */
function validatorParam(){
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if(beginDate==null || beginDate==''){
		alert("请选择开始时间");
		return false;
	}
	if(endDate==null || endDate==''){
		alert("请选择结束时间");
		return false;
	}
	return true;
}

function getList() {
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();

	// 网元
	var netYuan = $("#netYuan").val();

	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();

	// 区域
	var cityCode = $("#area").val();
	var tac = "";
	var eNodeBID = "";
	var areaHouse = "";
	
	
	var tacChecked=0;
	var enodebidCheck=0;
	var areaChecked=0;

	if (selectRadio == '5') {// 区域
		//alert("enter if (selectRadio == '5')");
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox")
		.each(
				function() {
					if ($(this).attr("checked")) {
						var areatBoxId = $(this).val();
						//alert("areatBoxId=" + areatBoxId);
						if (areatBoxId == '0') {// TAC
							tacChecked=1;
							tac = $("#tac").val();
						} else if (areatBoxId == '1') {// eNodeBID
							enodebidCheck=1;
							eNodeBID = $("#eNodeBID").val();
						} else if (areatBoxId == '2') {// 小区
							areaChecked=1;
							areaHouse = $("#areaHouse").val();
						}
				}
		});
	}

	// 用户组
	var groupId = $("#groupId").val();

	// 用户
	var userId = $("#userId").val();

	// 终端类型
	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();

	// apn
	var apnId = $("#apnId").val();
	
	params.setParam();
	
	if(validatorParam()){
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined" || datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		var columns = createColumns(selectRadio);
		datatable = $('#table').dataTable({
			"bPaginate" : true, // 翻页功能
			"bLengthChange" : false, // 改变每页显示数据数量
			"bFilter" : false, // 过滤功能
			"bSort" : true, // 排序功能
			"bInfo" : true,// 页脚信息
			"bAutoWidth" : true,// 自动宽度
			// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
			"iDisplayLength" : 50,
//			"sScrollX" : "100%",
			"sScrollXInner" : "110%",
			"bScrollCollapse" : true,
			"oLanguage" : {
				"sLengthMenu" : "每页显示 _MENU_条",
				"sZeroRecords" : "没有找到符合条件的数据",
				"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
				"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
				"sInfoEmpty" : "没有记录",
				"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
				"sSearch" : "搜索：",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "前一页",
					"sNext" : "后一页",
					"sLast" : "尾页"
				}
			},
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "../../businessAnalysis/paging/getPaging",

			"fnServerData" : function(sSource, aoData, fnCallback) {
				delete paras;
				paras = {
						"aoData" : JSON.stringify(aoData),
						"timeSize" : timeSize,
						"beginDate" : beginDate,
						"endDate" : endDate,
						"netYuan" : netYuan,
						"selectRadio" : selectRadio,
						"groupId" : groupId,
						"userId" : userId,
						"terminalBrandId" : terminalBrandId,
						"terminalModelId" : terminalModelId,
						"apnId" : apnId,						
						"cityCode" : cityCode,
						"tac" : tac,
						"eNodeBID" : eNodeBID,
						"areaHouse" : areaHouse,
						"tacChecked" :tacChecked,
						"enodebidCheck" :enodebidCheck,
						"areaChecked" :areaChecked
					};

				$.ajax({
					"type" : "post",
					"contentType" : "application/x-www-form-urlencoded",
					"url" : sSource,
					"dataType" : "json",
					"data" : paras, // 以json格式传递
					"success" : function(resp) {
						fnCallback(resp.pageDate);
						d = resp.allData;
					}
				});
			},
			columns : columns			
		});
	}
}

/**
 * 构造页面显示的列
 * @param selectRadio
 */
function createColumns(selectRadio) {
	//导出的列
	exportColumns = [];
	var columns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	//时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date"
	});
	exportColumns.push({
		"key":"report_date",
		"name":"时间",
		"value":""
	});
	//根据页面条件显示
	if (selectRadio == '5') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		
		columns.push({
			data : 'city_name'
		});
		exportColumns.push({
			"key":"city_name",
			"name":"地市",
			"value":""
		});
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox")
				.each(
						function() {
							if ($(this).attr("checked")) {
								var areatBoxId = $(this).val();
								if (areatBoxId == '0') {// TAC
									trObj.append($("<th >TAC</th>"));
									columns.push({
										data : "tac"
									});
									exportColumns.push({
										"key":"tac",
										"name":"TAC",
										"value":""
									});
								} else if (areatBoxId == '1') {// eNodeBID
									trObj.append($("<th >eNodeBID</th>"));
									columns.push({
										data : "enodebid"
									});
									exportColumns.push({
										"key":"enodebid",
										"name":"eNodeBID",
										"value":""
									});
								} else if (areatBoxId == '2') {// 小区
									trObj.append($("<th >小区</th>"));
									columns.push({
										data : "cell_name"
									});
									exportColumns.push({
										"key":"cell_name",
										"name":"小区",
										"value":""
									});
								}
							}
						});
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		columns.push({
			data : "group_name",
			render : function(value, type, row) {
				if(value==null){
					value = "";
				}
				return value;
			}
		
		});
		exportColumns.push({
			"key":"group_name",
			"name":"用户组",
			"value" :""
		});
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "msisdn"
		});
		exportColumns.push({
			"key":"msisdn",
			"name":"MSISDN",
			"value":""
		});
		trObj.append($("<th >IMSI</th>"));
		columns.push({
			data : "imsi"
		});
		exportColumns.push({
			"key":"imsi",
			"name":"IMSI",
			"value":""
		});
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
		columns.push({
			data : "terminal_brand"
		});
		exportColumns.push({
			"key":"terminal_brand",
			"name":"终端类型",
			"value":""
		});
		
		var terminalModelName="";
		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "terminal_model",
			render : function(value, type, row) {
				if(value == null){
					value = "";
				}
				return value;
			}
		});
		exportColumns.push({
			"key":"terminal_model",
			"name":"终端型号",
			"value":""
		});
	} else if (selectRadio == '3') {// apn
		trObj.append($("<th >APN</th>"));
		columns.push({
			data : "apn_name"
		});
		exportColumns.push({
			"key":"apn_name",
			"name":"APN",
			"value":""
		});
	}

	//MME
	trObj.append($("<th>MME</th>"));
	columns.push({
		data : "mme_name"
	});
	exportColumns.push({
		"key":"mme_name",
		"name":"MME",
		"value":""
	});	
	//一次Paging次数
	trObj.append($("<th>一次Paging次数</th>"));
	columns.push({
		data : "paging_once_number"
	});
	exportColumns.push({
		"key":"paging_once_number",
		"name":"一次Paging次数",
		"value":""
	});
	//一次Paging失败次数
	trObj.append($("<th>一次Paging失败次数</th>"));
	columns.push({
		data : "paging_once_fail_number",
		render : function(value, type, row) {
			var dateType = $('input:radio[name="timeSize"]:checked').val();
			var jspType = "paging";
			var failureTypeInfo = 1;//对应keyword 为0或者2
			var mme_name = row.mme_name == undefined ? "" : row.mme_name;
			var city_name = row.city_name == undefined ? "" : row.city_name;
			var tac = row.tac == undefined ? "" : row.tac;;
			var enodebid = row.enodebid == undefined ? "" : row.enodebid;
			var enodebName = "";
			var cell_name = row.cell_name == undefined ? "" : row.cell_name;
			var group_id = row.group_id == undefined ? "" : row.group_id;
			var msisdn = row.msisdn == undefined ? "" : row.msisdn;
			var terminal_model = row.terminal_model == undefined ? "" : row.terminal_model;
			var terminal_brand = row.terminal_brand == undefined ? "" : row.terminal_brand;
			var apn_name = row.apn_name == undefined ? "" : row.apn_name;
			var paramDate = row.report_date == undefined ? "" : row.report_date;
			
			return "<a href='#' style=\"text-decoration: underline;\" onclick=\"forwordInterfaceFailure('"
					+ dateType + "','"
					+ failureTypeInfo + "','"
					+ jspType + "','"
					+ mme_name + "','"
					+ city_name + "','"
					+ tac + "','"
					+ enodebid + "','"
					+ enodebName + "','"
					+ cell_name + "','"
					+ group_id + "','"
					+ msisdn + "','"
					+ terminal_model + "','"
					+ terminal_brand + "','"
					+ apn_name + "','"
					+ paramDate
					+ "')\"  >" + value + "</a>";
		}
	});
	exportColumns.push({
		"key":"paging_once_fail_number",
		"name":"一次Paging失败次数",
		"value":""
	});
	//一次Paging成功率
	trObj.append($("<th>一次Paging成功率(%)</th>"));
	columns.push({
		data : "paging_once_success_rate"
	});
	exportColumns.push({
		"key":"paging_once_success_rate",
		"name":"一次Paging成功率",
		"value":""
	});
	//一次Paging时延
	trObj.append($("<th>一次Paging时延</th>"));
	columns.push({
		data : "paging_once_delay_time"
	});
	exportColumns.push({
		"key":"paging_once_delay_time",
		"name":"一次Paging时延",
		"value":""
	});
	//二次Paging次数
	trObj.append($("<th>二次Paging次数</th>"));
	columns.push({
		data : "paging_twice_number"
	});
	exportColumns.push({
		"key":"paging_twice_number",
		"name":"二次Paging次数",
		"value":""
	});
	//二次Paging失败次数
	trObj.append($("<th>二次Paging失败次数</th>"));
	columns.push({
		data : "paging_twice_fail_number",
		render : function(value, type, row) {
			var dateType = $('input:radio[name="timeSize"]:checked').val();
			var jspType = "paging";
			var failureTypeInfo = 2;//对应keyword 位1或者3
			var mme_name = row.mme_name == undefined ? "" : row.mme_name;
			var city_name = row.city_name == undefined ? "" : row.city_name;
			var tac = row.tac == undefined ? "" : row.tac;;
			var enodebid = row.enodebid == undefined ? "" : row.enodebid;
			var enodebName = "";
			var cell_name = row.cell_name == undefined ? "" : row.cell_name;
			var group_id = row.group_id == undefined ? "" : row.group_id;
			var msisdn = row.msisdn == undefined ? "" : row.msisdn;
			var terminal_model = row.terminal_model == undefined ? "" : row.terminal_model;
			var terminal_brand = row.terminal_brand == undefined ? "" : row.terminal_brand;
			var apn_name = row.apn_name == undefined ? "" : row.apn_name;
			var paramDate = row.report_date == undefined ? "" : row.report_date;
			return "<a href='#' style=\"text-decoration: underline;\" onclick=\"forwordInterfaceFailure('"
					+ dateType + "','"
					+ failureTypeInfo + "','"
					+ jspType + "','"
					+ mme_name + "','"
					+ city_name + "','"
					+ tac + "','"
					+ enodebid + "','"
					+ enodebName + "','"
					+ cell_name + "','"
					+ group_id + "','"
					+ msisdn + "','"
					+ terminal_model + "','"
					+ terminal_brand + "','"
					+ apn_name + "','"
					+ paramDate
					+ "')\"  >" + value + "</a>";
		}
	});
	exportColumns.push({
		"key":"paging_twice_fail_number",
		"name":"二次Paging失败次数",
		"value":""
	});
	//二次Paging成功率
	trObj.append($("<th>二次Paging成功率(%)</th>"));
	columns.push({
		data : "paging_twice_success_rate"
	});
	exportColumns.push({
		"key":"paging_twice_success_rate",
		"name":"二次Paging成功率",
		"value":""
	});
	//二次Paging时延
	trObj.append($("<th>二次Paging时延</th>"));
	columns.push({
		data : "paging_twice_delay_time"
	});
	exportColumns.push({
		"key":"paging_twice_delay_time",
		"name":"二次Paging时延",
		"value":""
	});
	
	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

function exportExcel() {
	if (d) {
		paras['exportColumns'] = JSON.stringify(exportColumns);
		$.ajax({
			type : "POST",
			url : "../../businessAnalysis/paging/exportBigDataExcel?rand="
					+ Math.random(),
			dataType : "json",
			"data" : paras,
			success : function(data) {
			if (data.flag) {
				var url = "../../businessAnalysis/paging/downFiles?path="
						+ data.path;
				window.location.href = url;
			} else {
				alert(data.msgs);
			}
		}
		});
	} else {
		alert("请先查询数据！");
	}
}

function forwordInterfaceFailure(dateType,failureTypeInfo,jspType,mme_name,city_name,tac,
		enodebid,enodeb_name,cell_name,group_id,msisdn,terminal_model,terminal_brand,apn_name,paramDate) {
	//imsi terminal_brand(enodeb_name 暂无)
	var url = "/kpi/interfaceFailureLink/index?dateType=" + dateType +"&failureTypeInfo="+failureTypeInfo +"&jspType="+jspType+ "&mme_name="+mme_name
	+ "&paramDate=" + paramDate + "&interfaceType=2&signalType=100&type=" + params.dimension +"&tac_status="+params.tac_status
	+ "&eNodeBID_status=" + params.eNodeBID_status +"&village_status="+params.village_status 
	+ "&city_code=" +city_name+"&tai="+tac+"&enodeb_id="+enodebid +"&enodeb_name="+enodeb_name +"&terminal_brand="+terminal_brand
	+ "&cell_name=" +cell_name+"&group_id="+group_id+"&msisdn="+msisdn+"&user_terminal="+terminal_model+"&apn_name="+apn_name;   
	linkTab("接口故障", url);
}


// 下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}
/**
 * 显示树
 */
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
/**
 * 隐藏树
 */
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}